import flask_login
from werkzeug.security import check_password_hash, generate_password_hash
from wtforms import Form
from wtforms import StringField, PasswordField, BooleanField
from wtforms import validators
from wtforms.validators import DataRequired
from models import User


class Users(flask_login.UserMixin):
    def __init__(self, email=None, password=None, username=None, id=None):
        self.email = email
        self.password = password
        self.username = username
        self.id = None

    # Flask-Login integration
    def is_authenticated(self):
        return True

    def is_active(self):
        return True

    def is_anonymous(self):
        return False

    # TypeError: ObjectId('552f41e56a85f00dd043406b') is not JSON serializable
    def get_id(self):
        return str(self.id)

    def __unicode__(self):
        return self.username


class LoginForm(Form):
    username = StringField('username', validators=[DataRequired()])
    password = PasswordField('password', validators=[DataRequired()])
    remember_me = BooleanField('remember_me', default=False)

    def get_user(self):
        user = User.objects(username=self.username.data).first()
        return user

    def validate_name(self):
        user = self.get_user()
        if user:
            if not check_password_hash(user.password, self.password.data):
                # print('password error')
                return False
            else:
                return True

        else:
            # print('user error')
            return False

